<?php
require_once("dao/tournaments_dao.php");
require_once("dao/brackets_dao.php");

class tournament_controller extends abstract_controller {

	function prepare_model($request_params, Smarty $smarty_obj) { 
		$name = isset($_GET['name']) ? htmlentities($_GET['name']) : "";
		$admin = isset($_SESSION['admin']) ? $_SESSION['user'] : "";		
		if (empty($name)) header("Location: ?page=tournaments");
		$user = isset($_SESSION['user']) ? $_SESSION['user'] : "";
		
		$smarty_obj->assign('page',"tournament&name=$name");
		
		//Legger til en ny spiller .....
		$join = isset($_GET['join']) ? htmlentities($_GET['join']) : "";
		if(!empty($join)) {
			if (isLoggedIn()){
				$res = tournaments_dao::addPlayer($name, $user);
				$smarty_obj->assign('message', $res);
			} else {
				$smarty_obj->assign('message',"Du er ikke logget inn!");
			}
		} 
		
		$status = tournaments_dao::addPlayer($name, $user, true);
		if (is_null($status)){
			//fullt
		} else {
			$smarty_obj->assign('active',$status);
		}
		
		
		$tournament = tournaments_dao::readTournament($name);
		$smarty_obj->assign("info", $tournament->info);
		$smarty_obj->assign("rules", $tournament->rules);
		$smarty_obj->assign("name", $tournament->name);
		$smarty_obj->assign("activeplayers", count($tournament->users->user));
		$smarty_obj->assign("numberofplayers", $tournament->numberofplayers);
		$smarty_obj->assign("players", $tournament->users->user);
		$smarty_obj->assign("page_title", "Tournament");
		
		if($admin) {
			$smarty_obj->assign("admin",true);
		}
		
		if((string)tournaments_dao::getStatus($name) === "Started")
			$smarty_obj->assign("started", true);
		else $smarty_obj->assign("started", false);
				
		if(is_null(brackets_dao::getBracket($name))) {
			$smarty_obj->assign("brackets_generated", false);
		}
		else { 
			$smarty_obj->assign("brackets_generated", true);		
		}
	}
	
}
?>